<template>
    <view class="ai-chat-container">
        <!-- 页面头部 -->
        <page-header title="鼎和农业大模型" />
        
        <!-- 聊天消息区域 -->
        <scroll-view
            class="chat-messages"
            scroll-y="true"
            :scroll-top="scrollTop"
            scroll-with-animation="true"
            :enable-back-to-top="false"
            :show-scrollbar="false"
            ref="chatScroll">
            
            <!-- 欢迎消息 -->
            <view class="message-wrapper welcome-wrapper">
                <view class="message assistant welcome">
                    <view class="message-avatar ai-avatar">AI</view>
                    <view class="message-content welcome-content">
                        <view class="welcome-title">您好！我是您的AI助手，有什么可以帮您的吗？</view>
                        <!-- <view class="welcome-features">
                            <view class="feature-item">1.制定每日优先事项清单</view>
                            <view class="feature-item">2.使用番茄工作法管理时间</view>
                            <view class="feature-item">3.减少多任务处理，专注单一任务</view>
                            <view class="feature-item">4.定期休息保持精力充沛</view>
                        </view> -->
                    </view>
                </view>
            </view>
            
            <!-- 动态消息列表 -->
            <view
                v-for="(message, index) in messages"
                :key="index"
                class="message-wrapper">
                <!-- 时间显示 -->
                <view class="message-time">{{ formatTime(message.timestamp) }}</view>
                <!-- 消息内容 -->
                <view :class="['message', message.role]">
                    <view class="message-avatar" :class="{ 'ai-avatar': message.role === 'assistant', 'user-avatar': message.role === 'user' }">
                        {{ message.role === 'user' ? '' : 'AI' }}
                    </view>
                    <view class="message-content">
                        <!-- 如果有图片，先显示图片 -->
                        <image
                            v-if="message.image && message.role === 'user'"
                            :src="message.image"
                            class="message-image"
                            mode="aspectFit"
                            @error="onImageError" />
                        <!-- 消息文本内容 -->
                        <view v-html="formatMessage(message.content)"></view>
                    </view>
                </view>
            </view>
            
            <!-- 流式输出消息 -->
            <view v-if="streamingMessage" class="message-wrapper">
                <view class="message assistant streaming">
                    <view class="message-avatar ai-avatar">AI</view>
                    <view class="message-content">
                        <view v-html="formatMessage(streamingMessage)"></view>
                        <text class="cursor">▋</text>
                    </view>
                </view>
            </view>
            
            <!-- 加载指示器 -->
            <view v-if="isLoading && !streamingMessage" class="typing-indicator">
                <view class="typing-dots">
                    <view class="dot"></view>
                    <view class="dot"></view>
                    <view class="dot"></view>
                </view>
            </view>
        </scroll-view>
        
        <!-- 输入区域 -->
        <view class="chat-input-container">
            <!-- 图片预览 -->
            <view v-if="selectedImage" class="image-preview">
                <image :src="selectedImage" class="preview-image" mode="aspectFit" />
                <view class="remove-image" @click="removeImage">×</view>
            </view>
            
            <!-- 输入框和按钮 -->
            <view class="input-group">
                <view class="image-upload-btn" @click="chooseImage">
                    <image src="/static/images/upload-img.png" class="camera-icon" mode="aspectFit" />
                </view>
                <view class="input-wrapper">
                    <textarea
                        v-model="inputText"
                        class="chat-input"
                        placeholder="请输入"
                        :auto-height="true"
                        :maxlength="1000"
                        @confirm="sendMessage"
                        @input="onInputChange" />
                </view>
                <view
                    class="send-btn"
                    :class="{ disabled: !canSend }"
                    @click="sendMessage">
                    发送
                </view>
            </view>
        </view>
    </view>
</template>

<script>
import PageHeader from '@/components/PageHeader/index.vue'

export default {
    components: {
        PageHeader
    },
    data() {
        return {
            // API配置 - 我的
            // apiKey: 'sk-jZFoeRA0If26Dl91tfVGPrxrgwylG9w5QVWUzVIqr5SZuQ8W',
            apiKey: 'sk-y4MZiTBo15RAZZpsgZTM7cHZbEoQiFdSg6wTK8tJ33HXAhLQ',
            // 他们的
            // apiKey: 'sk-fb9FfnYfzGePQhcKSIijt8YfHJZ4ETdSExo029LXxa1MGUgG',
            selectedModel: 'KwooVa', // KwooVa支持多模态，KwooLa仅支持文本
            
            // 聊天数据
            messages: [],
            inputText: '',
            selectedImage: null,
            streamingMessage: '',
            
            // 状态控制
            isLoading: false,
            scrollTop: 0
        }
    },
    computed: {
        canSend() {
            return !this.isLoading && (this.inputText.trim() || this.selectedImage)
        }
    },
    onLoad() {
        // 每次进入都是新的聊天，不加载历史记录
        this.messages = []
        this.scrollToBottom()
    },
    onUnload() {
        // 页面卸载时清理状态
        this.isLoading = false
        this.streamingMessage = ''
    },
    methods: {
        // 选择图片
        chooseImage() {
            uni.chooseImage({
                count: 1,
                sizeType: ['compressed'],
                sourceType: ['album', 'camera'],
                success: (res) => {
                    const tempFilePath = res.tempFilePaths[0]
                    this.uploadImage(tempFilePath)
                },
                fail: (err) => {
                    console.error('选择图片失败:', err)
                    uni.showToast({
                        title: '选择图片失败',
                        icon: 'none'
                    })
                }
            })
        },
        
        // 上传图片到API
        async uploadImage(filePath) {
            uni.showLoading({ title: '上传图片中...' })
            
            try {
                const uploadResult = await new Promise((resolve, reject) => {
                    uni.uploadFile({
                        url: 'https://api.tgkwai.com/api/v1/attachments/upload',
                        filePath: filePath,
                        name: 'file',
                        formData: {
                            'type': 'image'
                        },
                        header: {
                            'X-Token': `Bearer ${this.apiKey}`
                        },
                        success: (res) => {
                            try {
                                const data = JSON.parse(res.data)
                                if (data.code === 200) {
                                    resolve(`https://static.tgkwai.com/uploads/${data.data}`)
                                } else {
                                    reject(new Error(data.msg || '上传失败'))
                                }
                            } catch (e) {
                                reject(new Error('解析响应失败'))
                            }
                        },
                        fail: reject
                    })
                })
                
                this.selectedImage = uploadResult
                uni.hideLoading()
                
            } catch (error) {
                uni.hideLoading()
                console.error('上传图片失败:', error)
                uni.showToast({
                    title: '上传图片失败',
                    icon: 'none'
                })
            }
        },
        
        // 移除选中的图片
        removeImage() {
            this.selectedImage = null
        },
        
        // 图片加载错误处理
        onImageError() {
            uni.showToast({
                title: '图片加载失败',
                icon: 'none'
            })
        },
        
        // 输入框内容变化
        onInputChange(e) {
            this.inputText = e.detail.value
        },
        
        // 发送消息
        async sendMessage() {
            if (!this.canSend) return
            
            const messageText = this.inputText.trim()
            const messageImage = this.selectedImage
            
            if (!messageText && !messageImage) return
            
            // 添加用户消息
            this.addMessage('user', messageText, messageImage)
            
            // 清空输入
            this.inputText = ''
            this.selectedImage = null
            
            // 开始加载
            this.isLoading = true
            this.scrollToBottom()
            
            try {
                await this.callAPI(messageText, messageImage)
            } catch (error) {
                console.error('发送消息失败:', error)
                uni.showToast({
                    title: '发送失败: ' + error.message,
                    icon: 'none'
                })
            } finally {
                this.isLoading = false
                this.streamingMessage = ''
            }
        },
        
        // 添加消息到列表
        addMessage(role, content, image = null) {
            this.messages.push({
                role,
                content,
                image,
                timestamp: new Date().toISOString()
            })
            this.scrollToBottom()
        },

        // 调用AI API
        async callAPI(message, image) {
            const url = 'https://api.tgkwai.com/api/v1/qamodel/chat/completions'

            // 构建当前消息
            let currentMessage
            if (image && this.selectedModel === 'KwooVa') {
                // 多模态消息格式
                currentMessage = {
                    role: "user",
                    content: [
                        {
                            type: "text",
                            text: message
                        },
                        {
                            type: "image_url",
                            image_url: {
                                url: image
                            }
                        }
                    ]
                }
            } else {
                // 纯文本消息格式
                currentMessage = {
                    role: "user",
                    content: message
                }
            }

            // 构建完整的消息历史（多轮对话支持）
            const conversationMessages = []

            // 添加历史消息（排除最后一条，因为那是当前正在发送的消息）
            const historyMessages = this.messages.slice(0, -1)

            historyMessages.forEach(msg => {
                if (msg.role === 'user') {
                    if (msg.image && this.selectedModel === 'KwooVa') {
                        conversationMessages.push({
                            role: "user",
                            content: [
                                {
                                    type: "text",
                                    text: msg.content || '图片消息'
                                },
                                {
                                    type: "image_url",
                                    image_url: {
                                        url: msg.image
                                    }
                                }
                            ]
                        })
                    } else {
                        conversationMessages.push({
                            role: "user",
                            content: msg.content || '图片消息'
                        })
                    }
                } else if (msg.role === 'assistant') {
                    conversationMessages.push({
                        role: "assistant",
                        content: msg.content
                    })
                }
            })

            // 添加当前消息
            conversationMessages.push(currentMessage)

            const requestBody = {
                model: this.selectedModel,
                messages: conversationMessages,
                stream: true, // 启用流式输出
                temperature: 0.7,
                max_tokens: 4096
            }

            return await this.handleStreamResponse(url, requestBody)
        },

        // 处理流式响应 - 使用uni.request
        async handleStreamResponse(url, requestBody) {
            return new Promise((resolve, reject) => {
                // 由于uni-app的uni.request不直接支持流式响应，
                // 我们改为使用普通请求，然后模拟流式输出效果
                uni.request({
                    url: url,
                    method: 'POST',
                    header: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${this.apiKey}`
                    },
                    data: {
                        ...requestBody,
                        stream: false // 暂时关闭流式，使用普通响应
                    },
                    success: (res) => {
                        console.log('返回信息')
                        console.log(res)
                        if (res.statusCode === 200) {
                            if(res?.data?.code === 401){
                                uni.showToast({
                                    title: res?.data?.msg || 'API密钥错误',
                                    icon: 'none'
                                })
                                reject(new Error(res?.data?.msg || 'API密钥错误'))
                                return
                            }
                            const content = res.data.choices?.[0]?.message?.content || ''
                            // 模拟流式输出效果
                            this.simulateStreamOutput(content)
                            resolve(content)
                        } else {
                            reject(new Error(`HTTP ${res.statusCode}: ${res.data?.error?.message || '请求失败'}`))
                        }
                    },
                    fail: (error) => {
                        reject(new Error(error.errMsg || '网络请求失败'))
                    }
                })
            })
        },

        // 模拟流式输出效果
        async simulateStreamOutput(fullContent) {
            if (!fullContent) return

            this.streamingMessage = ''
            const words = fullContent.split('')

            for (let i = 0; i < words.length; i++) {
                this.streamingMessage += words[i]
                this.scrollToBottom()
                // 控制输出速度，每个字符间隔50ms
                await new Promise(resolve => setTimeout(resolve, 50))
            }

            // 输出完成后添加到消息列表
            this.addMessage('assistant', fullContent)
            this.streamingMessage = ''
        },



        // 格式化消息内容
        formatMessage(content) {
            if (!content) return ''

            // 简单的格式化：换行和基本的markdown支持
            return content
                .replace(/\n/g, '<br>')
                .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
                .replace(/\*(.*?)\*/g, '<em>$1</em>')
        },

        // 格式化时间
        formatTime(timestamp) {
            if (!timestamp) return ''
            const date = new Date(timestamp)
            const now = new Date()
            const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
            const messageDate = new Date(date.getFullYear(), date.getMonth(), date.getDate())

            if (messageDate.getTime() === today.getTime()) {
                // 今天的消息只显示时间
                return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
            } else {
                // 其他日期显示日期和时间
                return date.toLocaleString('zh-CN', {
                    month: '2-digit',
                    day: '2-digit',
                    hour: '2-digit',
                    minute: '2-digit'
                })
            }
        },

        // 滚动到底部
        scrollToBottom() {
            this.$nextTick(() => {
                this.scrollTop = 999999
            })
        }
    }
}
</script>

<style lang="scss" scoped>
.ai-chat-container {
    display: flex;
    flex-direction: column;
    height: 100vh;
    background-color: #ffffff;
    overflow: hidden;
}

.chat-messages {
    flex: 1;
    padding: 20rpx 0;
    overflow-y: auto;
    box-sizing: border-box;
    /* 确保滚动区域不会超出容器 */
    height: 0; /* 配合flex: 1使用，确保正确的高度计算 */
}

.message-wrapper {
    margin-bottom: 40rpx;

    .message-time {
        font-size: 22rpx;
        color: #999;
        text-align: center;
        margin-bottom: 10rpx;
    }
}

.message {
    display: flex;
    align-items: flex-start;
    padding: 0 10rpx;
    box-sizing: border-box;

    &.user {
        justify-content: flex-end;

        .message-avatar {
            order: 1;
            margin-left: 20rpx;
            margin-right: 0;
        }

        .message-content {
            background: #007AFF;
            color: white;
            border-radius: 40rpx;
            border-bottom-right-radius: 10rpx;
            max-width: calc(100% - 120rpx); /* 减去头像和间距的宽度 */
        }
    }

    &.assistant {
        justify-content: flex-start;

        .message-avatar {
            margin-right: 20rpx;
            margin-left: 0;
        }

        .message-content {
            background: #F2F2F7;
            color: #000;
            border-radius: 40rpx;
            border-bottom-left-radius: 10rpx;
            max-width: calc(100% - 120rpx); /* 减去头像和间距的宽度 */
        }
    }

    &.streaming .message-content {
        position: relative;
    }
}

.message-avatar {
    width: 80rpx;
    height: 80rpx;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: bold;
    color: white;
    font-size: 28rpx;
    flex-shrink: 0;

    &.ai-avatar {
        background-image: url('/static/images/ai-avatar.png');
        background-size: cover;
        background-position: center;
    }

    &.user-avatar {
        background: #E5E5EA;
        background-image: url('/static/images/user-avatar.png');
        background-size: cover;
        background-position: center;
    }
}

.message-content {
    padding: 24rpx 32rpx;
    border-radius: 36rpx;
    word-wrap: break-word;
    word-break: break-all;
    line-height: 1.6;
    font-size: 28rpx;
    box-sizing: border-box;
    overflow-wrap: break-word;
}

.message-image {
    max-width: 200rpx;
    max-height: 150rpx;
    border-radius: 16rpx;
    margin-bottom: 16rpx;
    display: block;
    object-fit: cover;
}

.cursor {
    color: #4CAF50;
    animation: blink 1s infinite;
    margin-left: 4rpx;
}

@keyframes blink {
    0%, 50% { opacity: 1; }
    51%, 100% { opacity: 0; }
}

.typing-indicator {
    display: flex;
    align-items: center;
    margin-bottom: 40rpx;
    margin-left: 100rpx;
}

.typing-dots {
    display: flex;
    gap: 8rpx;
}

.dot {
    width: 16rpx;
    height: 16rpx;
    border-radius: 50%;
    background: #4CAF50;
    animation: typing 1.4s infinite ease-in-out;
}

.dot:nth-child(1) { animation-delay: -0.32s; }
.dot:nth-child(2) { animation-delay: -0.16s; }

@keyframes typing {
    0%, 80%, 100% { transform: scale(0); }
    40% { transform: scale(1); }
}

.chat-input-container {
    padding: 30rpx 40rpx;
    background: white;
    border-top: 1px solid #e0e0e0;
    box-sizing: border-box;
    /* 确保在安全区域内 */
    padding-bottom: calc(30rpx + env(safe-area-inset-bottom));
}

.image-preview {
    position: relative;
    margin-bottom: 20rpx;
    display: inline-block;
    max-width: 100%;
}

.preview-image {
    max-width: 200rpx;
    max-height: 150rpx;
    border-radius: 16rpx;
    border: 2px solid #e0e0e0;
    object-fit: cover;
    display: block;
}

.remove-image {
    position: absolute;
    top: -8rpx;
    right: -8rpx;
    background: #ff4444;
    color: white;
    border-radius: 50%;
    width: 40rpx;
    height: 40rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 20rpx;
    font-weight: bold;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.2);
}

.input-group {
    display: flex;
    gap: 20rpx;
    align-items: center;
    box-sizing: border-box;
    background: #F2F2F7;
    border-radius: 50rpx;
    padding: 10rpx;
}

.image-upload-btn {
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;

    .camera-icon {
        width: 80rpx;
        height: 80rpx;
    }
}

.input-wrapper {
    flex: 1;
    min-width: 0; /* 防止flex子项溢出 */
}

.chat-input {
    width: 100%;
    min-height: 40rpx;
    max-height: 200rpx;
    border: none;
    background: transparent;
    font-size: 28rpx;
    box-sizing: border-box;
    line-height: 1.4;
    resize: none;
    outline: none;
}

.send-btn {
    background: #007AFF;
    color: white;
    border-radius: 30rpx;
    padding: 15rpx 30rpx;
    font-size: 28rpx;
    flex-shrink: 0;
    transition: background-color 0.3s;

    &.disabled {
        background: #ccc;
    }

    &:not(.disabled):active {
        background: #0056CC;
    }
}

/* 欢迎消息特殊样式 */
.welcome-wrapper {
    .message-time {
        display: none; /* 欢迎消息不显示时间 */
    }
}

.welcome-content {
    background: #F2F2F7 !important;
    color: #000 !important;
    border: none !important;
}

.welcome-title {
    font-weight: bold;
    font-size: 26rpx;
}

.welcome-features {
    margin: 20rpx 0;
}

.feature-item {
    margin-bottom: 8rpx;
    font-size: 26rpx;
    opacity: 0.9;
}

.welcome-footer {
    margin-top: 20rpx;
    font-size: 26rpx;
    opacity: 0.9;
}

/* 响应式优化 */
@media screen and (max-width: 750rpx) {
    .message-content {
        max-width: calc(100% - 100rpx);
        font-size: 26rpx;
        padding: 20rpx 28rpx;
    }

    .message-avatar {
        width: 70rpx;
        height: 70rpx;
        font-size: 24rpx;
    }

    .chat-input {
        font-size: 26rpx;
        padding: 20rpx 70rpx 20rpx 28rpx;
        min-height: 80rpx;
    }

    .send-btn {
        width: 80rpx;
        height: 80rpx;
        font-size: 28rpx;
    }

    .image-upload-btn {
        font-size: 28rpx;
        right: 20rpx;
    }
}
</style>
